const express = require("express");
const router = express.Router();
const db = require("../model/db");
// 作者：简帮松
//文章的添加
router.post("/", async (req, res) => {
    const data = await db.Article.create(req.body);
    res.send(data);
})

// 作者：简帮松
//文章的修改部分
router.put("/:id", async (req, res) => {
    await db.Article.updateOne({
        _id: req.params.id
    }, req.body);

    res.send({
        "code": 0,
        "message": "修改成功",
        "data": true
    });


})

//作者：简帮松
//文章删除部分
router.delete("/:id", async (req, res) => {
    await db.Article.deleteOne({
        _id: req.params.id
    })
    res.send({
        "code": 0,
        "message": "删除成功",
        "data": true
    });
})
// 作者:简帮松
//得到所有文章，默认升序。
router.get("/", async (req, res) => {
    if (!req.query.field) {//默认按什么排序
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    let str = req.query.field;
    if (req.query.sort === "desc") {
        str = "-" + str;
    }
    let page = parseInt(req.query.page);
    let limit = parseInt(req.query.limit);
    if (!page) {
        page = 1;
    }
    if (!limit) {
        limit = 5;
    }
    let condition = {};

    if (req.query.key) {
        let exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        condition = {
            $or: [
                { title: { $regex: exp } },
                { description: { $regex: exp } },

            ]
        }

    }
    const data = await db.Article.find(condition).sort(str).skip((page - 1) * limit).limit(limit);


    res.send({
        "code": 0,
        "msg": "",
        "count": await db.Article.count(condition),
        "data": data
    });
})

router.get("/:id", async (req, res) => {
    const data = await db.Article.findById(req.params.id)
    res.send(data);
})

module.exports = router;